<template>
  <div class="app-container">
    <search-form
      ref="header"
      :search-data="ruleForm"
      :search-form="searchData"
      :search-handle="searchHandle"
    >
      <slot>
        <el-popover placement="bottom" :width="240" trigger="click">
          <template #reference>
            <el-button size="mini" style="float:right;padding:7px 10px;">
              <i
                class="el-icon-setting"
                style="font-size:16px;margin-right:5px;"
              ></i
              >设置列</el-button
            >
          </template>
          <div style="max-height:350px;width:100%;overflow:auto;">
            <el-checkbox-group v-model="headChecked">
              <template v-for="item in checkboxHeads" :key="item">
                <el-checkbox
                  :label="item"
                  style="margin:10px 8px 0 0;"
                ></el-checkbox>
              </template>
            </el-checkbox-group>
          </div>
          <div class="drop-footer m_t10" style="text-align:center;">
            <el-button type="primary" size="mini" @click="handleSetTitle"
              >确定</el-button
            >
          </div>
        </el-popover>
      </slot>
    </search-form>
    <el-table
      :data="tableData"
      style="width: 100%;"
      :header-cell-style="{
        padding: '10px 0',
        color: 'rgb(0, 127, 235)',
        backgroundColor: '#fff',
      }"
      :height="tableHeight"
      v-loading="loading"
      size="medium"
    >
      <el-table-column
        prop="heatSourceName"
        label="热源名称"
        fixed
      ></el-table-column>
      <el-table-column
        prop="heatStationName"
        label="换热站"
        fixed
        align="center"
      ></el-table-column>
      <el-table-column
        prop="systemName"
        label="系统名称"
        fixed
        align="center"
      ></el-table-column>
      <el-table-column
        prop="userType"
        label="用户类型"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="heatModel"
        label="供热模式"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="heatType"
        label="节能类型"
        align="center"
      ></el-table-column>
      <el-table-column label="数据时间" prop="date" align="center" width="140">
      </el-table-column>
      <el-table-column
        prop="控制模式.value"
        label="控制模式"
        align="center"
        :formatter="formatKZ"
      >
      </el-table-column>
      <el-table-column
        prop="水箱液位.value"
        label="水箱液位"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="手动给定.value"
        label="手动给定"
        align="center"
      ></el-table-column>

      <template v-for="(item, index) in tableColumn" :key="index">
        <el-table-column
          :label="item.name"
          :prop="item.prop"
          align="center"
          v-if="!item.isShow"
        >
          <template v-for="(child, cIdx) in item.child" :key="cIdx">
            <el-table-column
              :label="child.name"
              align="center"
              v-if="!child.isShow"
            >
              <template #default="scope">
                <span v-html="valueFormatter(scope.row, child.prop)"> </span>
              </template>
            </el-table-column>
          </template>
        </el-table-column>
      </template>
    </el-table>
  </div>
</template>
<script>
import { getRunDataNew } from "@/api/runData";
import { onMounted, reactive, toRefs } from "vue";
import { useStore } from "vuex";
import { getSendList, getJieNengType } from "@/api/remoteSend";
import searchForm from "@/components/SearchForm/index.vue";
import utils from "./index";
import { parseTime } from "@/utils/index";
import heightMinxin from "@/utils/tableHeight.mixin";
export default {
  name: "runData",
  mixins: [heightMinxin],
  components: { searchForm },
  methods: {
    formatKZ(row) {
      if (typeof row.控制模式 !== "undefined") {
        let control = row.控制模式.value;
        if (control == 0) {
          return "手动";
        }
        if (control == 1) {
          return "分时开度";
        }
        if (control == 2) {
          return "分时温度";
        }
        if (control == 3) {
          return "分时流量";
        }
        if (control == 4) {
          return "恒定流量";
        }
        if (control == 5) {
          return "点对点温度";
        }
      } else {
        return null;
      }
    },
  },
  setup() {
    const store = useStore();
    const state = reactive({
      ruleForm: {
        heatSourceId: "",
        heatingType: "",
        userType: "",
        heatModel: "",
        heatSystemIds: [],
      },
      searchData: [
        {
          type: "Select",
          prop: "heatSourceId",
          options: [],
          placeholder: "选择热源",
          change: () => {
            getHeatSystemData();
          },
        },
        {
          type: "Select",
          prop: "userType",
          options: [],
          placeholder: "用户类型",
          change: () => {
            getHeatSystemData();
          },
        },
        {
          type: "Select",
          prop: "heatModel",
          options: [],
          placeholder: "供热模式",
          change: () => {
            getHeatSystemData();
          },
        },
        {
          type: "Select",
          prop: "heatingType",
          options: [],
          placeholder: "节能类型",
          change: () => {
            getHeatSystemData();
          },
        },
        {
          type: "Select",
          prop: "heatSystemIds",
          multiple: true,
          options: [],
          collapse: true,
          width: 240,
          placeholder: "选择系统",
          change: () => {},
        },
      ],
      searchHandle: [
        {
          label: "搜索",
          type: "primary",
          handle: () => {
            getList();
          },
        },
      ],
      loading: false,
      tableColumn: [],
      tableData: [],
      headChecked: [], //checkbox选中列
      checkboxHeads: [],
    });
    onMounted(() => {
      init();
    });

    const init = async () => {
      await getHeatSourceData();
      const userArr = await getHeatTypeList("userType");
      state.searchData[1].options = userArr;
      const modelArr = await getHeatTypeList("heatModel");
      state.searchData[2].options = modelArr;
      const typeArr = await getHeatTypeList("heatingType");
      state.searchData[3].options = typeArr;
      await getTableHeads();
      getList();
    };

    const valueFormatter = (row, prop) => {
      if (prop == "一次温差") {
        if (row["一供温度"] !== undefined && row["一回温度"] !== undefined) {
          let num = row["一供温度"].value - row["一回温度"].value;
          return num.toFixed(2);
        } else {
          return null;
        }
      }
      if (prop == "一次压差") {
        if (row["一供压力"] != undefined && row["一回压力"] != undefined) {
          let oneYaValue = row["一供压力"].value - row["一回压力"].value;
          return oneYaValue.toFixed(2);
        } else {
          return null;
        }
      }
      if (prop == "二次温差") {
        if (row["二供温度"] != undefined && row["二回温度"] != undefined) {
          let num1 = row["二供温度"].value - row["二回温度"].value;
          return num1.toFixed(2);
        } else {
          return null;
        }
      }
      if (prop == "二次压差") {
        if (row["二供压力"] != undefined && row["二回压力"] != undefined) {
          let num = row["二供压力"].value - row["二回压力"].value;
          return num.toFixed(2);
        } else {
          return null;
        }
      }
      if (row[prop] && row[prop].value !== undefined) {
        return row[prop].value;
      } else {
        return null;
      }
    };
    /**获取热源列表 */
    const getHeatSourceData = () => {
      const { sourceData } = store.getters;
      state.searchData[0].options = sourceData;
      if (sourceData.length > 0) {
        state.ruleForm.heatSourceId = sourceData[0].value;
        getHeatSystemData();
      }
    };

    const getHeatTypeList = (type) => {
      return new Promise((resolve) => {
        getJieNengType({ typeName: type }).then((res) => {
          if (res.data.success) {
            const result = res.data.data.map((item) => {
              return { label: item[type], value: item[type] };
            });
            resolve(result);
          }
        });
      });
    };
    // /**获取系统数据 */
    const getHeatSystemData = () => {
      state.ruleForm.heatSystemIds = [];
      state.searchData[4].options = [];
      const { heatSourceId, heatingType, userType, heatModel } = state.ruleForm;
      getSendList({ heatSourceId, heatingType, userType, heatModel }).then(
        (res) => {
          if (res.data.success) {
            let data = res.data.data;
            const result = data.map((item) => {
              return { label: item.name, value: item.id };
            });
            state.searchData[4].options = result;
            if (result.length > 0) {
              let idsArr = result.slice(0, 5);
              state.ruleForm.heatSystemIds = idsArr.map((v) => v.value);
            }
          }
        }
      );
    };
    /**数据查询 */
    const getList = () => {
      state.loading = true;
      const { heatSystemIds } = state.ruleForm;
      let systemData = state.searchData[4].options;
      let idsArr = [];
      if (heatSystemIds.length == 0) {
        idsArr = systemData.map((item) => item.value);
      } else {
        idsArr = heatSystemIds;
      }
      getRunDataNew({ heatSystemIds: idsArr }).then((res) => {
        if (res.data.success) {
          state.loading = false;
          let list = res.data.data;
          const result = list.map((item) => {
            Object.keys(item).forEach((val) => {
              if (item[val]["date"]) {
                item["date"] = parseTime(
                  item[val]["date"],
                  "{y}-{m}-{d} {h}:{i}"
                );
              }
            });
            return item;
          });

          state.tableData = result;
        } else {
          state.loading = false;
        }
      });
    };
    /**表头获取 */
    const getTableHeads = () => {
      const { tableTitle } = utils;
      const result = tableTitle.map((item) => {
        if (item.child) {
          const child = item.child.map((v) => {
            return { ...v, isShow: false };
          });
          item.child = child;
        }

        item.isShow = false;

        return item;
      });
      state.tableColumn = result;
      state.checkboxHeads = utils.getNameArr(tableTitle);
    };

    /**自定义列设置 */
    const handleSetTitle = async () => {
      let list = state.tableColumn;
      let checkArr = state.headChecked;

      for (let i = 0; i < list.length; i++) {
        let item = list[i];
        if (item.child) {
          for (let j = 0; j < item.child.length; j++) {
            const { prop } = item.child[j];
            if (checkArr.includes(prop)) {
              item.child[j]["isShow"] = true;
            } else {
              item.child[j]["isShow"] = false;
            }
          }
          const flag = await filterFlag(item.child);

          if (flag) {
            item.isShow = true;
          } else {
            item.isShow = false;
          }
        }
      }

      state.tableColumn = list;
    };

    const filterFlag = (arr) => {
      const result = arr.every((v) => v.isShow === true);
      return result;
    };

    return {
      ...toRefs(state),
      handleSetTitle,
      valueFormatter,
    };
  },
};
</script>
<style lang="less"></style>
